package server

import (
	"net"

	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials"
	"starsine.cn/appTpl/cmn/config/aconf"
	"starsine.cn/appTpl/cmn/logs"
	"starsine.cn/appTpl/cmn/utils"
	"starsine.cn/appTpl/svccenter/registry/grpc/scregistryproto"
)

type GRpcServer struct {
	addr              string
	tls               bool
	certFile, keyFile string
}

func CreateGRpcServer() *GRpcServer {
	p := new(GRpcServer)

	p.addr = aconf.GetString("SvcCenter.Addr", "localhost:20000", aconf.WithENV("sc_addr"))
	p.tls = aconf.GetBool("SvcCenter.Tls", true, aconf.WithENV("sc_tls"))
	p.certFile = utils.Path(aconf.GetString("SvcCenter.CertFile", "conf/x509/cert.pem", aconf.WithENV("sc_cert")))
	p.keyFile = utils.Path(aconf.GetString("SvcCenter.KeyFile", "conf/x509/key.pem", aconf.WithENV("sc_key")))

	logs.Debugf("SC CreateGRpcServer: addr=%s, tls=%t, certFile=%s, keyFile=%s", p.addr, p.tls, p.certFile, p.keyFile)

	return p
}

func (p *GRpcServer) Start() {
	lis, err := net.Listen("tcp", p.addr)
	if err != nil {
		logs.Errorf("GRpcServer start to listen fail, err: %s", err)
	}

	var opts []grpc.ServerOption
	if p.tls {
		creds, err := credentials.NewServerTLSFromFile(p.certFile, p.keyFile)
		if err != nil {
			logs.Errorf("GRpcServer start to NewServerTLSFromFile fail, err: %s", err)
		}
		opts = []grpc.ServerOption{grpc.Creds(creds)}
	}
	grpcServer := grpc.NewServer(opts...)
	scregistryproto.RegisterRegistryProtoServer(grpcServer, &RegistryProtoServer{})
	go grpcServer.Serve(lis)
}
